package com.ruoyi.common.core.utils.uuid;

import java.util.Random;


/**
 * ID生成器工具类
 * 
 * @author ruoyi
 */
public class IdUtils
{
    /**
     * 获取随机UUID
     * 
     * @return 随机UUID
     */
    public static String randomUUID()
    {
        return UUID.randomUUID().toString();
    }

    /**
     * 简化的UUID，去掉了横线
     * 
     * @return 简化的UUID，去掉了横线
     */
    public static String simpleUUID()
    {
        return UUID.randomUUID().toString(true);
    }

    /**
     * 获取随机UUID，使用性能更好的ThreadLocalRandom生成UUID
     * 
     * @return 随机UUID
     */
    public static String fastUUID()
    {
        return UUID.fastUUID().toString();
    }

    /**
     * 简化的UUID，去掉了横线，使用性能更好的ThreadLocalRandom生成UUID
     * 
     * @return 简化的UUID，去掉了横线
     */
    public static String fastSimpleUUID()
    {
        return UUID.fastUUID().toString(true);
    }
    
    static private SnowflakeIdWorker id;
	static {
		Random random=new Random();
		int workId=random.nextInt(32);
		int datacenterId=random.nextInt(32);
		id=new SnowflakeIdWorker(workId,datacenterId);
	}
	/**
	 * 获取18位的唯一主键
	 * @return
	 */
	static public  long getId(){
		try {
			return id.nextId();
		}catch(RuntimeException e) {
			//时间被调整回去了，可能是时间同步引起的
			if(e.toString().contains("Clock moved backwards")) {
				try {Thread.sleep(50);} catch (InterruptedException e1) {}
				return id.nextId();
			} else {
				throw e;
			}
		}
		
	}
	
	/**
	 * 返回18位字符串的唯一ID
	 * @return
	 */
	static public  String getStrId(){
		return id.nextId()+"";
	}
}
